# -*- coding: utf-8 -*-
# @Time    : 2024/11/10 13:57
# @Author  : CHNJX
# @File    : module.py
# @Desc    :

# api/routes/module.py
from flask import Blueprint, request
from app.model import Module
from app.utils.response_handler import response_with_handler, success_response, error_response

module_bp = Blueprint('module', __name__)


@module_bp.route('/', methods=['GET'])
@response_with_handler
def get_modules():
    """获取所有功能模块"""
    modules = Module.get_all_modules()
    return success_response([module.to_dict() for module in modules])


@module_bp.route('/<int:module_id>', methods=['GET'])
@response_with_handler
def get_module(module_id):
    """获取单个功能模块"""
    module = Module.get_module_by_id(module_id)
    if module is None:
        return error_response("模块不存在", code=404)
    return success_response(module.to_dict())


@module_bp.route('/mapping', methods=['GET'])
@response_with_handler
def get_module_mapping():
    """获取模块名称到目录名的映射"""
    modules = Module.get_all_modules()
    mapping = {}
    
    for module in modules:
        if module.directory_name:
            mapping[module.name] = module.directory_name
    
    return success_response(mapping)


@module_bp.route('/', methods=['POST'])
@response_with_handler
def create_module():
    """创建功能模块"""
    data = request.get_json()
    if not data or 'name' not in data:
        return error_response("缺少必要的参数: name", code=400)

    module = Module.create_module(data)
    return success_response(module.to_dict(), "模块创建成功")


@module_bp.route('/<int:module_id>', methods=['PUT'])
@response_with_handler
def update_module(module_id):
    """更新功能模块"""
    module = Module.get_module_by_id(module_id)
    if module is None:
        return error_response("模块不存在", code=404)

    data = request.get_json()
    updated_module = module.update_module(data)
    return success_response(updated_module.to_dict(), "模块更新成功")


@module_bp.route('/<int:module_id>', methods=['DELETE'])
@response_with_handler
def delete_module(module_id):
    """删除功能模块"""
    result = Module.delete_module(module_id)
    if not result:
        return error_response("模块不存在", code=404)
    return success_response(message="模块删除成功")